package com.tech.platform.cms.authz.sso.utils;

import cn.hutool.core.util.StrUtil;
import com.tech.platform.cms.authz.sso.config.SsoYmlConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class JwtRedisUtils {

    private static final String HGT_TOKEN = "sso:jwt:hgt:%s:%d";

    private static final String HGC_TOKEN = "sso:jwt:hgc:%d";

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private SsoYmlConfig ssoYmlConfig;

    public void saveHgtToken(String client,int userId,String token){
        String key = StrUtil.format(HGT_TOKEN,client,userId);
        redisTemplate.opsForValue().set(key,token);
        redisTemplate.expire(key,ssoYmlConfig.getRedisHgtTokenExpireTime(), TimeUnit.MINUTES);
    }

    public String getHgtToken(String client,int userId){
        String key = StrUtil.format(HGT_TOKEN,client,userId);
        Object token = redisTemplate.opsForValue().get(key);
        if(token == null){
            return null;
        }

        return token.toString();
    }

    public void saveHgcToken(int userId,String token){
        String key = StrUtil.format(HGC_TOKEN,userId);
        redisTemplate.opsForValue().set(key,token);
        redisTemplate.expire(key,ssoYmlConfig.getRedisHgcTokenExpireTime(), TimeUnit.MINUTES);
    }

    public String getHgcToken(int userId){
        String key = StrUtil.format(HGC_TOKEN,userId);
        Object token = redisTemplate.opsForValue().get(key);
        if(token == null){
            return null;
        }

        return token.toString();
    }
}
